package org.dh2580.delay.queue.bean.executor;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: hao.deng
 * @Date: 2019/5/14-下午7:52
 */
public class SimpleExecutor {
    private ThreadPoolExecutor executor;

    public SimpleExecutor(int coreSize, int maxSize, String poolNamePrefix) {

        BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>();

        ThreadFactory threadFactory = new SimpleThreadFactory(poolNamePrefix, true);

        executor = new ThreadPoolExecutor(coreSize, maxSize, 30, TimeUnit.MINUTES, blockingQueue, threadFactory);

    }

    public void execute(Runnable runnable) {
        executor.execute(runnable);

    }

    public <T> Future<T> submit(Callable<T> callable) {
        return executor.submit(callable);
    }

    public void shutdown() throws InterruptedException {

        executor.shutdown();

        while (executor.awaitTermination(1, TimeUnit.MINUTES)) { }
    }

}
